package com.ganmiao.web.portal.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ganmiao.server.sys.vo.SysUserVo;
import com.ganmiao.server.user.context.UserAuthContext;
import com.ganmiao.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Author zero.yin
 * @Date 2022/9/12 23:05
 * @Desc
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        SysUserVo loginUser = UserAuthContext.getLoginUser();
        this.setFieldValByName("createdUserId", Objects.nonNull(loginUser) ? loginUser.getUserId() : null, metaObject);
        this.setFieldValByName("createdUserName", Objects.nonNull(loginUser) ? loginUser.getUserName() : "", metaObject);
        this.setFieldValByName("createdTime", DateUtil.getDate(), metaObject);
        this.setFieldValByName("updatedUserId", Objects.nonNull(loginUser) ? loginUser.getUserId() : null, metaObject);
        this.setFieldValByName("updatedUserName", Objects.nonNull(loginUser) ? loginUser.getUserName() : "", metaObject);
        this.setFieldValByName("updatedTime", DateUtil.getDate(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        SysUserVo loginUser = UserAuthContext.getLoginUser();
        this.setFieldValByName("updatedUserId", Objects.nonNull(loginUser) ? loginUser.getUserId() : null, metaObject);
        this.setFieldValByName("updatedUserName", Objects.nonNull(loginUser) ? loginUser.getUserName() : "", metaObject);
        this.setFieldValByName("updatedTime", DateUtil.getDate(), metaObject);
    }

}
